package com.ruoyi.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.SysAttachment;
import com.ruoyi.system.service.ISysAttachmentService;
import lombok.AllArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.Instant;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * 附件Controller
 *
 * @author zht
 * @date 2022-07-04
 */
@AllArgsConstructor
@RestController
@RequestMapping("/system/attachment" )
public class SysAttachmentController extends BaseController {

    @Autowired
    private ISysAttachmentService iSysAttachmentService;

    /**
     * 查询附件列表
     */
    @GetMapping("/list")
    public TableDataInfo list(SysAttachment sysAttachment)
    {
        startPage();
        List<SysAttachment> list = iSysAttachmentService.list(getLambdaQueryWrapper(sysAttachment));
        return getDataTable(list);
    }

    /**
     * 查询附件列表（不分页）
     */
    @GetMapping("/listAll")
    public AjaxResult listAll(SysAttachment sysAttachment)
    {
        List<SysAttachment> list = iSysAttachmentService.list(getLambdaQueryWrapper(sysAttachment));
        return AjaxResult.success(list);
    }

    /**
     * 导出附件列表
     */
    @Log(title = "附件" , businessType = BusinessType.EXPORT)
    @GetMapping("/export" )
    public AjaxResult export(SysAttachment sysAttachment) {
        LambdaQueryWrapper<SysAttachment> lqw = new LambdaQueryWrapper<SysAttachment>(sysAttachment);
        List<SysAttachment> list = iSysAttachmentService.list(lqw);
        ExcelUtil<SysAttachment> util = new ExcelUtil<SysAttachment>(SysAttachment. class);
        return util.exportExcel(list, "attachment" );
    }

    /**
     * 获取附件详细信息
     */
    @GetMapping(value = "/{fileId}" )
    public AjaxResult getInfo(@PathVariable("fileId" ) Long fileId) {
        return AjaxResult.success(iSysAttachmentService.getById(fileId));
    }

    /**
     * 新增附件
     */
    @Log(title = "附件" , businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody SysAttachment sysAttachment) {
        return toAjax(iSysAttachmentService.save(sysAttachment) ? 1 : 0);
    }

    /**
     * 修改附件
     */
    @Log(title = "附件" , businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody SysAttachment sysAttachment) {
        return toAjax(iSysAttachmentService.updateById(sysAttachment) ? 1 : 0);
    }

    /**
     * 删除附件
     */
    @Log(title = "附件" , businessType = BusinessType.DELETE)
    @DeleteMapping("/{fileIds}" )
    public AjaxResult remove(@PathVariable Long[] fileIds) {
        return toAjax(iSysAttachmentService.removeByIds(Arrays.asList(fileIds)) ? 1 : 0);
    }

    /**
     * 附件上传请求
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("module") String module,
                                 @RequestParam("businessid") String businessid) throws Exception {
        String userName = SecurityUtils.getUsername();
        Date now = Date.from(Instant.now());
        String originalFileName = null;
        try {
            //获取原始文件名、后缀和文件大小
            originalFileName = file.getOriginalFilename();
            long size = file.getSize()/ 1024;
            String extension = FileUploadUtils.getExtension(file);
            // 上传并返回新文件路径名称
            String pathFileName = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
            //String url = serverConfig.getUrl() + fileName;
            SysAttachment attachment = new SysAttachment();
            attachment.setFileName(originalFileName);
            attachment.setModule(module);
            attachment.setBusinessid(businessid);
            attachment.setPath(pathFileName);
            attachment.setAttachmentSize(size);
            attachment.setSuffix(extension);
            attachment.setCreateBy(userName);
            attachment.setCreateTime(now);
            attachment.setUpdateBy(userName);
            attachment.setUpdateTime(now);
            iSysAttachmentService.save(attachment);
            return AjaxResult.success(String.format("文件：%s，上传成功！", originalFileName),attachment);
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(String.format("文件：%s，上传失败！", originalFileName));
        }

    }

    private LambdaQueryWrapper getLambdaQueryWrapper(SysAttachment sysAttachment){
        LambdaQueryWrapper<SysAttachment> lqw = new LambdaQueryWrapper<SysAttachment>();
        if (StringUtils.isNotBlank(sysAttachment.getFileName())){
            lqw.like(SysAttachment::getFileName ,sysAttachment.getFileName());
        }
        if (StringUtils.isNotBlank(sysAttachment.getModule())){
            lqw.eq(SysAttachment::getModule ,sysAttachment.getModule());
        }
        if (StringUtils.isNotBlank(sysAttachment.getBusinessid())){
            lqw.eq(SysAttachment::getBusinessid ,sysAttachment.getBusinessid());
        }
        if (StringUtils.isNotBlank(sysAttachment.getType())){
            lqw.eq(SysAttachment::getType ,sysAttachment.getType());
        }
        if (StringUtils.isNotBlank(sysAttachment.getPath())){
            lqw.eq(SysAttachment::getPath ,sysAttachment.getPath());
        }
        if (StringUtils.isNotBlank(sysAttachment.getNote())){
            lqw.eq(SysAttachment::getNote ,sysAttachment.getNote());
        }
        if (sysAttachment.getAttachmentSize() != null){
            lqw.eq(SysAttachment::getAttachmentSize ,sysAttachment.getAttachmentSize());
        }
        if (StringUtils.isNotBlank(sysAttachment.getSuffix())){
            lqw.eq(SysAttachment::getSuffix ,sysAttachment.getSuffix());
        }
        lqw.orderByDesc(SysAttachment::getCreateTime);
        return lqw;
    }
}
